# *-* coding:utf-8 *-*
import sys
import time

# 底层算法原理
# def in_polygon_ray(polygon, pt):
#     num_pts = len(polygon)
#
#     junction_count = 0
#
#     for i in range(num_pts - 1):
#         pt1 = polygon[i]
#         pt2 = polygon[i + 1]
#
#         if (pt.y >= pt1.y and pt.y <= pt2.y) or (pt.y >= pt2.y and pt.y <= pt1.y):
#             t = (pt.y - pt1.y) / (pt2.y - pt1.y)
#             x = pt1.x + t * (pt2.x - pt1.x)
#
#             if pt.x == x:
#                 return "ONSIDE"
#
#             if pt.x > x:
#                 junction_count += 1
#
#     if junction_count % 2 == 1:
#         return "INSIDE"
#     else:
#         return "OUTSIDE"


# # 逐行匹配方法
# import csv
# from shapely.geometry import Polygon, Point
#
#
# # 打开CSV文件
# path = r'F:\geo\ok_geo.csv'
# csv.field_size_limit(1000000000)  # 设置字段限制大小为最大值
# with open(path, encoding='utf-8') as f:
#     reader = csv.reader(f)
#     # 跳过标题行
#     next(reader)
#     # counter = 1
#     # 读取每行的数据，只读取前7列
#     t1 = time.time()
#     for row in reader:
#         # if counter >= 100:
#         #     break
#         id = row[0]
#         pid = row[1]
#         deep = row[2]
#         name = row[3]
#         ext_path = row[4]
#         if len(row[6])<10:
#             continue
#         if deep != '2':
#             continue
#         data = row[6].replace(';',',')
#         # 创建Shapely Polygon
#         poly = Polygon(list(map(lambda x: tuple(map(float, x.split())), data.split(','))))
#         # counter += 1
#         # 定义一个点用于测试，新疆维吾尔自治区 昌吉回族自治州 呼图壁县，耗时： 8.375591516494751
#         point = Point(86.871532, 44.179362)
#
#         # 判断点在多边形内
#         if poly.contains(point):
#             print(f"Point inside polygon {id}")
#             print('找到位置：',ext_path)
#             break
#
#         # print('找不到位置')
#     t2 = time.time()
#     print('耗时：',t2-t1)



# # 转化为dataframe，进行分级匹配缩小范围
# import pandas as pd
# from shapely.geometry import Polygon, Point
# level=2
#
# # 打开CSV文件
# path = r'F:\geo\ok_geo.csv'
# df = pd.read_csv(path)
# # 筛选deep = row[2]，ext_path = row[4]，poly = row[6]
# # 定义一个点用于测试，新疆维吾尔自治区 昌吉回族自治州 呼图壁县，耗时： 7.869028091430664
# point = Point(86.871532, 44.179362)
# time1 = time.time()
# df1 = df[df['deep'] == level]
# for index, row in df1.iterrows():
#     if len(row['polygon'])<10:
#         continue
#     data = row['polygon'].replace(';', ',')
#     # 创建Shapely Polygon
#     poly = Polygon(list(map(lambda x: tuple(map(float, x.split())), data.split(','))))
#     if poly.contains(point):
#         print(f"Point inside polygon {id}")
#         print('找到位置：', row['ext_path'])
#         break
# time2 = time.time()
# print('耗时：',time2-time1)




# 转化为dataframe，筛选省级，然后在下一级，最快
import pandas as pd
from shapely.geometry import Polygon, Point


def search_geo(df, point, output):
    result = ''
    for i, r in df.iterrows():
        if len(r['polygon']) < 10:
            continue
        data = r['polygon'].replace(';', ',')
        # 创建Shapely Polygon
        poly = Polygon(list(map(lambda x: tuple(map(float, x.split())), data.split(','))))
        if poly.contains(point):
            result = r[output]
            break
        else:
            continue
    return result

def run(df, point):
    df1 = df[df['deep'] == 1]
    ids = search_geo(df1, point, 'id')
    if ids == '':
        print('找不到位置')
        sys.exit()
    df2 = df[df['pid'] == ids]
    res = search_geo(df2, point, 'ext_path')
    print('找到位置：', res)
    return res


if __name__ == '__main__':
    # 定义一个点用于测试，新疆维吾尔自治区 昌吉回族自治州 呼图壁县，耗时： 5.429507255554199
    point = Point(86.871532, 44.179362)
    # 打开CSV文件
    path = r'F:\geo\ok_geo.csv'
    time1 = time.time()
    df = pd.read_csv(path)
    res = run(df, point)
    time2 = time.time()
    print('耗时：', time2 - time1)







